package db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DbConnection {
	private static final String USER = "root";
	private static final String PASSWORD = "123456";
	private static final String PARAMETER8 = "characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8"; //Mysql8以上版本连接参数需设置时区
	private static final String URL = "jdbc:mysql://localhost:3306/contacts521?"+ PARAMETER8;
	private static Connection conn;
	
	/**
	 * 获得一个数据库连接对象
	 * @return java.sql.Connection实例
	 */
	public static Connection getConnection() {
		try {
			
			Class.forName("com.mysql.cj.jdbc.Driver"); 
			if (conn == null) {
				conn = DriverManager.getConnection(URL, USER, PASSWORD);
			} else {
				return conn;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}
	public static void close(ResultSet rs,PreparedStatement ps) {
		try{
			if(rs!=null) {
				rs.close();	
				rs = null;
			}
			if(ps!=null) {
				ps.close();
				ps=null;
			}
			if(conn!=null) {
				conn.close();
				conn=null;
			}
		}catch(SQLException e) {
			e.printStackTrace();
		}
	}
}